package com.huangmb.anymark.app.utils;

import android.support.annotation.NonNull;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.huangmb.anymark.app.app.AnyMarkApplication;

/**
 * 基于高德地图的定位器
 *
 * @author hmb
 * @version 1.0
 * @since 2016/4/18 17:06
 */
public class Locator {
    private static AMapLocationClient mLocationClient;
    public static LatLng lastPos = null;

    /**
     * 定位一次
     *
     * @param locationListener 回调
     */
    public static void startLocationOnce(LocationListener locationListener) {
        startLocation(locationListener, true);
    }

    /**
     * 持续定位，定位间隔10秒
     *
     * @param locationListener 定位回调
     */
    public static void startLocation(LocationListener locationListener) {
        startLocation(locationListener, false);
    }

    /**
     * 定位
     * @param locationListener 定位回调
     * @param once             是否仅定位一次
     */
    public static void startLocation(final LocationListener locationListener, final boolean once) {
        AMapLocationClientOption option = new AMapLocationClientOption();
        //高精度定位模式
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(once);
        if (!once) {
            option.setInterval(10000);
        }
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(AnyMarkApplication.getInstance());
        }
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if(once){
                    stopLocation();
                }
                if (locationListener == null) {
                    return;
                }
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    lastPos = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                    locationListener.onLocationChanged(aMapLocation);
                } else {
                    locationListener.onFail(aMapLocation);
                }

            }
        });
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    public static void stopLocation() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }

    public interface LocationListener {
        void onLocationChanged(@NonNull AMapLocation aMapLocation);

        void onFail(AMapLocation aMapLocation);
    }
}
